/**
 * Created by zhangxiaoyu on 16/12/10.
 */
angular.module('hyt.myWaybillCtrl',[])

  .controller('WaybillListCtrl',function($scope,$filter,$ionicModal,MyWaybills,Storage,WaybillDetail,$cordovaHdoitBle,$ionicLoading,$state,$ionicPopup,getPrinter,WaybillGoods){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.waybillSearch={
      parameter:{
        WAYBILL_NO:'',
        WAYBILL_STATUS:'',
        WAYBILL_DATE:'',
        WAYBILL_DATE_TO:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    MyWaybills.getWaybillData($scope.waybillSearch);
    $scope.$on('WaybillList.Updated', function() {
      $scope.waybillData=MyWaybills.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      MyWaybills.getWaybillData($scope.waybillSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      MyWaybills.getMoreWaybillData($scope.waybillSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return MyWaybills.hasNextPage();
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      console.log('EndDate');
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchWaybill=function(){
      $scope.waybillSearch.parameter.WAYBILL_DATE=$scope.startDate;
      $scope.waybillSearch.parameter.WAYBILL_DATE_TO=$scope.endDate;
      $scope.waybillSearch.parameter.WAYBILL_STATUS=$('#waybillState').val();
      MyWaybills.getWaybillData($scope.waybillSearch);
      $scope.modal.hide();
    };
    $scope.$on('$destroy', function() {
      $scope.modal.remove();
    });
    $ionicModal.fromTemplateUrl('templates/tab-workbench/myWaybill/searchWaybill.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.goDetail=function(id){
      Storage.set('wayId',id);
      $state.go('detailTab.detail');
    };
    var printMsg={
      deptId:userMsg.rows.baseDeptId,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    getPrinter.getPrintSet(JSON.stringify(printMsg));
    $scope.$on('GetPrint.Updated', function() {
      $scope.printsMsg = getPrinter.getResult().rows;
      if ($scope.printsMsg.company_name==null){
        $scope.printsMsg.company_name='存根标题';
      }
      if ($scope.printsMsg.phone==null){
        $scope.printsMsg.phone='客服电话';
      }
      if ($scope.printsMsg.remark==null){
        $scope.printsMsg.remark='责任条文';
      }
    });
    $scope.printWaybill=function(id){
      var wayDetail={
        wayId:id,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      WaybillDetail.getWaybillDetail(JSON.stringify(wayDetail));
      WaybillGoods.getWaybillGoods(JSON.stringify(wayDetail));
    };
    $scope.$on('WaybillDetail.Updated', function() {
      $scope.waybillDetail = WaybillDetail.getResult().rows;
      switch ($scope.waybillDetail.DELIVERY_TYPE){
        case '0' :
          $scope.DELIVERY_TYPE = '自提';
          break;
        case '1' :
          $scope.DELIVERY_TYPE = '送货';
          break;
        case '2' :
          $scope.DELIVERY_TYPE = '上楼';
          break;
        default :
          break;
      }
      if(isConeccted=='0'){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请先连接打印机", duration: 1500
        });
        $state.go('printSetting');
      }else{
        if ($scope.printsMsg.goods_flag==1){
          if ($scope.printsMsg.print_behave==0){
            var confirmPopup = $ionicPopup.confirm({
              scope:$scope,
              template: '<div class="list">' +
              '<div class="item" style="height: 55px"><div class="row" style="font-size: 16px">' +
              '<div class="col-60">货物标贴份数:</div>' +
              '<input type="number" class="col-25" ng-model="printsMsg.goods_pieces" maxlength="20" style="text-align: right;margin-top: -7px;margin-right: 2px">' +
              '<div class="col-15">份</div>'+
              '</div>' +
              '</div>' +
              '</div>',
              okText:'确定',
              cancelText:'取消'
            });
            confirmPopup.then(function(res) {
              if (res) {
                if ($scope.printsMsg.company_flag==1){
                  readyToPrintStub(0);
                }
                if ($scope.printsMsg.shipper_flag==1){
                  readyToPrintStub(1);
                }
                if ($scope.printsMsg.goods_flag==1){
                  for (var i=0;i<$scope.printsMsg.goods_pieces;i++){
                    readyToPrintGoods();
                  }
                }
                $state.go('myWaybill');
              }
            });
          }else {
            if ($scope.printsMsg.company_flag==1){
              readyToPrintStub(0);
            }
            if ($scope.printsMsg.shipper_flag==1){
              readyToPrintStub(1);
            }
            if ($scope.printsMsg.goods_flag==1){
              for (var i=0;i<$scope.waybillGoods[0].PIECES;i++){
                readyToPrintGoods();
              }
            }
          }
        }else {
          if ($scope.printsMsg.company_flag==1){
            readyToPrintStub(0);
          }
          if ($scope.printsMsg.shipper_flag==1){
            readyToPrintStub(1);
          }
        }
      }
    });
    $scope.$on('WaybillGoods.Updated', function() {
      var result=WaybillGoods.getResult();
      $scope.waybillGoods=result.rows;
    });
    var isConeccted;
    window.setInterval(getBleName,1000);
    function getBleName(){
      //蓝牙设备名称
      $cordovaHdoitBle.bluetoothName(function(success){
        if(success!=null){
          isConeccted='1';
        }
        else {
          isConeccted='0';
        }
      },function(err){
        isConeccted='0';
      });
    }
    function readyToPrintStub(i){
      var line;
      if ($scope.waybillDetail.DESTINATION_NAME!=null&&$scope.waybillDetail.DESTINATION_STATION!=null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_NAME+" → "+$scope.waybillDetail.DESTINATION_STATION;
      }else if ($scope.waybillDetail.DESTINATION_NAME!=null&&$scope.waybillDetail.DESTINATION_STATION==null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_NAME;
      }else if ($scope.waybillDetail.DESTINATION_NAME==null&&$scope.waybillDetail.DESTINATION_STATION!=null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_STATION;
      }
      if ($scope.waybillDetail.AGENCY_FUND==undefined||$scope.waybillDetail.AGENCY_FUND==null){
        $scope.waybillDetail.AGENCY_FUND='0.00';
      }
      if ($scope.waybillDetail.PAY_COLLECTION==undefined||$scope.waybillDetail.PAY_COLLECTION==null){
        $scope.waybillDetail.PAY_COLLECTION='0.00';
      }
      if ($scope.waybillDetail.FREIGHT_AMOUNT==undefined||$scope.waybillDetail.FREIGHT_AMOUNT==null){
        $scope.waybillDetail.FREIGHT_AMOUNT='0.00';
      }
      if ($scope.waybillDetail.PAYMENT_FREIGHT==undefined||$scope.waybillDetail.PAYMENT_FREIGHT==null){
        $scope.waybillDetail.PAYMENT_FREIGHT='0.00';
      }
      if ($scope.waybillDetail.BACK_NOW==undefined||$scope.waybillDetail.BACK_NOW==null){
        $scope.waybillDetail.BACK_NOW='0.00';
      }
      if ($scope.waybillDetail.OWE_TO_RETURN==undefined||$scope.waybillDetail.OWE_TO_RETURN==null){
        $scope.waybillDetail.OWE_TO_RETURN='0.00';
      }
      //设置打印机页面
      var startPageOption = {"pageWidth":600,"pageHeight":400};
      $cordovaHdoitBle.startPageZhike(startPageOption);
      //打印文本
      var companyNmae = {"x":10,"y":5,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.company_name,companyNmae);

      var waybillNO={"x":10,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("运单号:",waybillNO);

      var waybillNOTxt={"x":110,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.WAYBILL_NO,waybillNOTxt);

      var date={"x":330,"y":65,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($filter('date')(new Date($scope.waybillDetail.WAYBILL_DATE),'yyyy-MM-dd'),date);

      var phone={"x":420,"y":17.5,"textSize":2,"fontName":"斜体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.phone,phone);

      if (i==0){
        var companyStub={"x":490,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike("存根",companyStub);
      }else if(i==1){
        var shipperStub={"x":460,"y":65,"textSize":5,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike("发货方留存",shipperStub);
      }

      //线路及货物信息
      var lineAndGoods={"x":10,"y":105,"textSize":15,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike(line,lineAndGoods);

      //送货方式
      var deliveryType={"x":380,"y":145,"textSize":3,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.DELIVERY_TYPE,deliveryType);

      //收货人
      var consignee={"x":10,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("收货方",consignee);

      //收货人名称
      var consigneeName={"x":110,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.CONSIGNEE.substring(0,4),consigneeName);

      //收货人电话
      var consigneePhone={"x":210,"y":145,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.CONSIGNEE_PHONE,consigneePhone);

      //发货人
      var shipper={"x":10,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("发货方",shipper);

      //发货人名称
      var shipperName={"x":110,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.SHIPPER.substring(0,4),shipperName);

      //发货人电话
      var shipperPhone={"x":210,"y":175,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.SHIPPER_PHONE,shipperPhone);

      //代收、代收垫付
      var collection={"x":10,"y":215,"textSize":4,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike('代收:'+$scope.waybillDetail.AGENCY_FUND+' '+'代收垫付:'+$scope.waybillDetail.PAY_COLLECTION,collection);

      //运费、运费垫付
      var freight={"x":10,"y":245,"textSize":4,"fontName":"宋体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike('运费:'+$scope.waybillDetail.FREIGHT_AMOUNT+' '+'运费垫付:'+$scope.waybillDetail.PAYMENT_FREIGHT,freight);

      //信息费
      var informationFee={"x":10,"y":285,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike('现返:'+$scope.waybillDetail.BACK_NOW+' '+'欠返:'+$scope.waybillDetail.OWE_TO_RETURN,informationFee);

      //到站信息
      if ($scope.waybillDetail.DESTINATION_NAME!=null){
        var destinationNote={"x":10,"y":315,"textSize":2,"fontName":"宋体","bold":false,"rotate":false};
        $cordovaHdoitBle.printTextZhike($scope.waybillDetail.DESTINATION_NAME+'  '+$scope.waybillDetail.destinationPhone,destinationNote);
      }

      //备注
      var remark={"x":10,"y":345,"width":520,"height":64,"fontSize":2,"rotate":0,"bold":1,"underline":false,"reverse":false};
      $cordovaHdoitBle.multilineText($scope.printsMsg.remark,remark);

      //开票人
      var drawer={"x":380,"y":315,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("开票人:"+userMsg.rows.cname,drawer);

      //扫码跟踪
      var tracking={"x":470,"y":215,"textSize":4,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike("扫码跟踪",tracking);

      //打印二维码
      var QRCode = {"x":450,"y":90,"size":3};
      $cordovaHdoitBle.printQRcodeZhike("http://www.xyt56.net/html/scanning.html?wayId="+$scope.waybillDetail.ID,QRCode);
      $cordovaHdoitBle.doPrint();
      $cordovaHdoitBle.gotoMarklabel();
    }
    function readyToPrintGoods(){
      var line;
      if ($scope.waybillDetail.DESTINATION_NAME!=null&&$scope.waybillDetail.DESTINATION_STATION!=null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_NAME+" → "+$scope.waybillDetail.DESTINATION_STATION;
      }else if ($scope.waybillDetail.DESTINATION_NAME!=null&&$scope.waybillDetail.DESTINATION_STATION==null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_NAME;
      }else if ($scope.waybillDetail.DESTINATION_NAME==null&&$scope.waybillDetail.DESTINATION_STATION!=null){
        line=$scope.waybillDetail.DEPARTURE_STATION+" → "+$scope.waybillDetail.DESTINATION_STATION;
      }
      //设置打印机页面
      var startPageOption = {"pageWidth":600,"pageHeight":430};
      $cordovaHdoitBle.startPageZhike(startPageOption);
      //打印文本
      var companyNmae = {"x":10,"y":-5,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.company_name,companyNmae);

      var phone={"x":420,"y":7.5,"textSize":2,"fontName":"斜体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.printsMsg.phone,phone);

      //运单号
      var waybillNO={"x":10,"y":80,"textSize":20,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.WAYBILL_NO,waybillNO);

      //线路
      var lines={"x":10,"y":160,"textSize":20,"fontName":"黑体","bold":true,"rotate":false};
      $cordovaHdoitBle.printTextZhike(line,lines);

      //打印一维码
      var oneCode = {"x":10,"y":280,"type":'128','width':1,'height':85,'rotate':false};
      $cordovaHdoitBle.printBarcodeZhike($scope.waybillDetail.WAYBILL_NO,oneCode);

      var massage={"x":10,"y":380,"textSize":1,"fontName":"宋体","bold":false,"rotate":false};
      $cordovaHdoitBle.printTextZhike($scope.waybillDetail.WAYBILL_NO+'  '+$filter('date')(new Date($scope.waybillDetail.WAYBILL_DATE),'yyyy-MM-dd'),massage);

      $cordovaHdoitBle.doPrint();
      $cordovaHdoitBle.gotoMarklabel();
    }
  })
  .controller('WaybillDetailCtrl',function($scope,$filter,$ionicModal,WaybillDetail,$stateParams,Storage,WaybillGoods,DownLoadAbnormalImg,DownLoadRectiptImg,$timeout){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var wayDetail={
      wayId:Storage.get('wayId'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    var downLoadImg={
      wayBillId:Storage.get('wayId'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    WaybillDetail.getWaybillDetail(JSON.stringify(wayDetail));
    WaybillGoods.getWaybillGoods(JSON.stringify(wayDetail));
    DownLoadRectiptImg.getDownLoadImg(JSON.stringify(downLoadImg));
    $scope.$on('WaybillDetail.Updated', function() {
      $scope.waybillDetail=WaybillDetail.getResult().rows;
      switch ($scope.waybillDetail.WAYBILL_STATUS){
        case '0' :
          $scope.WAYBILL_STATUS = '已承运';
          break;
        case '1' :
          $scope.WAYBILL_STATUS = '已装车';
          break;
        case '2' :
          $scope.WAYBILL_STATUS = '在途中';
          break;
        case '3' :
          $scope.WAYBILL_STATUS = '已到站';
          break;
        case '4' :
          $scope.WAYBILL_STATUS = '已中转';
          break;
        case '5' :
          $scope.WAYBILL_STATUS = '送货中';
          break;
        case '6' :
          $scope.WAYBILL_STATUS = '已签收';
          break;
        default :
          break;
      }
      switch ($scope.waybillDetail.PAYMENT_METHOD){
        case 0 :
          $scope.PAYMENT_METHOD = '现付';
          break;
        case 1 :
          $scope.PAYMENT_METHOD = '到付';
          break;
        case 2 :
          $scope.PAYMENT_METHOD = '回付';
          break;
        case 3 :
          $scope.PAYMENT_METHOD = '月结';
          break;
        case 4 :
          $scope.PAYMENT_METHOD = '货到打卡';
          break;
        case 5 :
          $scope.PAYMENT_METHOD = '欠付';
          break;
        case 6 :
          $scope.PAYMENT_METHOD = '代扣';
          break;
        case 7 :
          $scope.PAYMENT_METHOD = '多笔付';
          break;
        default :
          break;
      }
      switch ($scope.waybillDetail.DELIVERY_TYPE){
        case '0' :
          $scope.DELIVERY_TYPE = '自提';
          break;
        case '1' :
          $scope.DELIVERY_TYPE = '送货';
          break;
        case '2' :
          $scope.DELIVERY_TYPE = '上楼';
          break;
        default :
          break;
      }
    });
    $scope.$on('WaybillGoods.Updated', function() {
      var result=WaybillGoods.getResult();
      if (result.rows!=undefined){
        $scope.waybillGoods=result.rows;
      }else {
        $scope.waybillGoods=null;
      }
    });
    $scope.$on('DownLoadRectiptImg.Updated', function() {
      var result=DownLoadRectiptImg.getResult();
      $scope.imgData=result.rows;
      if (result.rows!=undefined){
        $scope.showloading=false;
      }else {
        $timeout(function(){
          $scope.showloading=false;
        },1000);
      }
    });
    //点击图片放大
    $scope.showBigImage = function (imageName) {  //传递一个参数（图片的URl）
      $scope.Url = imageName;                   //$scope定义一个变量Url，这里会在大图出现后再次点击隐藏大图使用
      $('.tabs').removeClass("show").addClass("hide");
      $('#bigImg').show(500);
    };
    $scope.hideBigImage = function () {
      $('#bigImg').hide(500);
      $('.tabs').removeClass("hide").addClass("show");
    };
  })
  .controller('WaybillProcessCtrl',function($scope,$filter,$ionicModal,WaybillRecord,Storage){
    var loginMsg=Storage.get('user');
    var waybillRecord={
      wayId:Storage.get('wayId'),
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    WaybillRecord.getRecord(JSON.stringify(waybillRecord));
    $scope.$on('WaybillRecord.Updated', function() {
      var waybillProcess=WaybillRecord.getResult().rows;
      $scope.processFirst=waybillProcess[0];
      var processData=[];
      var j;
      for(var i=1;i<waybillProcess.length;i++){
        j=i-1;
        processData[j]=waybillProcess[i];
      }
      $scope.processData=processData;
    });
  })
